package com.lu.spzx.manager.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.lu.spzx.manager.mapper.CategoryMapper;
import com.lu.spzx.model.vo.product.CategoryExcelVo;

import java.util.List;

// 不可以交给 Spring 管理
public class ExcelListener<T> extends AnalysisEventListener<T> {

    // 每隔 5 条存储数据库,实际使用中可以 100 条,然后清理 list,方便内存回收
    private static final int BATCH_COUNT = 100;

    // 缓存的数据
    private List cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    // 获取 mapper 对象
    private CategoryMapper categoryMapper;

    public ExcelListener(CategoryMapper categoryMapper) {
        this.categoryMapper = categoryMapper;
    }

    // 每解析一行数据就会调用一次该方法
    @Override
    public void invoke(T o, AnalysisContext analysisContext) {
        CategoryExcelVo data = (CategoryExcelVo) o;
        cachedDataList.add(data);
        // 达到 BATCH_COUNT 了,就需要去存储一次数据库,防止数据几万条数据在内存,容易 OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // excel 解析完毕以后需要执行的代码
        // 这里也要保存数据,确保最后遗留的数据也存储到数据库
        saveData();
    }

    private void saveData() {
        this.categoryMapper.batchInsert(cachedDataList);
    }
}
